<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no">
	<title>登录</title>
	<link rel="shortcut icon" href="#" />
	<link rel="stylesheet" href="../layui/css/layui.css" />
	<script type="text/javascript" src="../layui/layui.js"></script>
	<script type="text/javascript" src="../js/jquery1.9.1.js"></script>
	<script type="text/javascript" src="../js/axios.min.js"></script>
	<script type="text/javascript" src="../js/common.js"></script>
</head>

<body>
	<div class="layui-container" style="margin-top: 200px;">
		<div class="layui-row">
			<div class="layui-col-md6 layui-col-md-offset2">
				<form class="layui-form" lay-filter="login-form">
					<div class="layui-form-item">
						<label class="layui-form-label">用户名：</label>
						<div class="layui-input-block">
							<input type="text" name="username" placeholder="请输入用户名" class="layui-input">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label">密码：</label>
						<div class="layui-input-block">
							<input type="password" name="password" placeholder="请输入密码" class="layui-input">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label">身份：</label>
						<div class="layui-input-block">
							<input type="radio" name="userRoleId" value="3" title="学生" checked>
							<input type="radio" name="userRoleId" value="2" title="老师">
							<input type="radio" name="userRoleId" value="1" title="管理员">
						</div>
					</div>
					<div class="layui-form-item">
						<div class="layui-input-block">
							<!--
								type="button" 这个属性很关键，没有这个会重定向，请求走不了
							-->
							<button type="button" class="layui-btn" lay-submit
								lay-filter="login-form-submit">登录</button>
						</div>
					</div>
					<!-- 更多表单结构排版请移步文档左侧【页面元素-表单】一项阅览 -->
				</form>
			</div>
		</div>
	</div>
</body>
<script>
	// 加载layui组件
	layui.use(["form", "layer"], function (form, layer) {
		//提交登录表单
		form.on('submit(login-form-submit)', function (d) {
			var data = d.field;
			console.log(data);
			if ($.trim(data.username) == "") {
				layer.alert("用户名不能为空");
				return;
			}
			if ($.trim(data.password) == "") {
				layer.alert("用户密码不能为空");
				return;
			}
			axios({
				method: 'post',
				url: '/users/login',
				baseURL: serverPath,
				data: data,
				withCredentials: true,
				responseType: 'json',
			}).then(function (response) {
				console.log(response);
				//登录成功后，jwt存入localstorage
				localStorage.setItem("token", response.data.data.token);

				location.href = "main.html";
			})
				.catch(function (error) {
					console.log(error);
					layer.alert(error.response.data.error)
				});
			return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
		});
	});
</script>

</html>
